<template>
	<com-page allowScroll :bg-color="skinColor.color_bg_1">
		<view style="line-height: 0;">
			<view @tap="handlePreview(img)" v-for="(img, i) in currentChapter.content">
				<com-image class="comic_reader_image" :class="'comic_reader_image_' + (i + 1)" lazy-load mode="widthFix" :src="img" :referer="currentChapter.referer || ''"></com-image>
			</view>	
		</view>	
		<view class="position-fixed-cover" :style="{
			'visibility': skinMode == 'night' ? 'visible' : 'hidden',
			'background-color': 'rgba(0,0,0,.2)'
		}"></view>
		<view class="position-fixed-cover y-flex y-align-center y-justify-center"
		:style="{
			'background-color': skinColor.color_bg_1,
			'visibility': loading ? 'visible' : 'hidden'
		}">
			<com-loading :visible="loading" :color="skinColor.color_1" size="50"></com-loading>
		</view>
		<view class="comic-reader-center" @tap="controlsShow = true"></view>	
		<view class="position-fixed-cover y-flex" v-show="controlsShow">
			<view class="local-ducment-nav-bar-box" :style="{'background-color': skinColor.color_bg_1}">
				<com-nav-bar :color="skinColor.color_1" status-color="rgba(0,0,0,0)" bg-color="rgba(0,0,0,0)">
					<template #title>
						<com-text lines="2" class="y-flex-1 ml-20 mr-10" weight="bold" line-height="40" size="35"
						:color="skinColor.color_1"
						:value="loading ? '加载中' : (currentChapter.title || (detail.title + '第' + currentChapter.index + '话'))"></com-text>
					</template>
				</com-nav-bar>
			</view>
			<view class="y-flex-1" @tap="controlsShow = false"></view>	
			<view class="local-ducment-tabbar-box" :style="{'background-color': skinColor.color_bg_1}">
				<view class="y-flex y-row y-align-center y-justify-between page-padding-gap pt-30 pb-20">
					<view class="y-flex y-align-center" @tap="handleCatalog">
						<com-icon name="sort" :color="skinColor.color_1" size="40"></com-icon>
						<text class="fs-26 y-flex-1 ml-30 mr-30 mt-10" :style="{color: skinColor.color_1}">目录</text>
					</view>
					<view class="y-flex y-align-center" @tap="$store.dispatch('setting/switchSkinMode')">
						<com-icon :name="skinMode == 'night' ? 'creative_fill' : 'creative'" :color="skinColor.color_1" size="40"></com-icon>
						<text class="fs-26 y-flex-1 ml-30 mr-30 mt-10" :style="{color: skinColor.color_1}">{{skinMode == 'night' ? '日间' : '夜间'}}</text>
					</view>
					<view class="y-flex y-align-center" @tap="handlePrev">
						<com-icon name="round_right" style="transform: rotateZ(180deg);" :color="skinColor.color_1" size="40"></com-icon>
						<text class="fs-26 y-flex-1 ml-30 mr-30 mt-10" :style="{color: skinColor.color_1}">上一话</text>
					</view>
					<view class="y-flex y-align-center" @tap="handleNext">
						<com-icon name="round_right" :color="skinColor.color_1" size="40"></com-icon>
						<text class="fs-26 y-flex-1 ml-30 mr-30 mt-10" :style="{color: skinColor.color_1}">下一话</text>
					</view>
				</view>
				<com-safe-bottom></com-safe-bottom>
			</view>
		</view>
		<com-modal title="记录提示" :content="'本次阅读到 第' + (current + 1) + '话-第' + start + '张图片\n\n是否保存此次阅读位置'"
		:visible.sync="modalShow"
		:bg-color="skinColor.color_bg_2"
		:title-color="skinColor.color_1"
		:content-color="skinColor.color_2"
		cancel-text="取消保存"
		confirm-text="保存位置"
		@confirm="updatePositon"
		@cancel="handleCancel"></com-modal>
	</com-page>
</template>

<script>
	import appMixin from '@/common/mixin/app.js'
	import { openDB, closeDB, insert, select, update } from '@/assets/database'
	export default {
		mixins: [appMixin],
		computed: {
			history () {
				return this.$store.getters['setting/GET_HISTORY']
			},
			fontSize () {
				return this.$store.getters['setting/GET_DOCUMENT_FONT_SIZE']
			},
			fontFamily () {
				return this.detail?.fontFamily
			},
			pageType () {
				return this.$store.getters['setting/GET_DOCUMENT_PAGE_TYPE']
			},
			lineHeight () {
				return this.$store.getters['setting/GET_DOCUMENT_LINE_HEIGHT']
			},
			bgColor () {
				return this.$store.getters['setting/GET_DOCUMENT_BG_COLOR'] || this.themes[0].bgColor
			},
			color () {
				return this.$store.getters['setting/GET_DOCUMENT_TEXT_COLOR'] || this.themes[0].color
			},
			network () {
				return this.$store.getters['network/GET']
			},
			currentChapter () {
				const index = this.chapters.findIndex(c => c.index == (this.current + 1))
				return this.chapters[index] || {}
			}
		},
		data () {
			return {
				loading: true,//加载
				modalShow: false,
				settingShow: false,
				controlsShow: false,
				chapters: [],
				context: {},//正文
				detail: {},//详情
				catalog: [],//章节列表
				record: {},//阅读记录
				current: 0,//当前章节定位
				start: 1//当前页首字符全文位置
			}
		},
		onReady() {
			this.$utils.setFullscreen(true)
			this.catalog = this.$Route.query.chapters
			this.context = this.$Route.query.context
			this.detail = this.$Route.query.detail
			this.current = parseInt(this.$Route.query.current || 0)
			this.start = parseInt(this.$Route.query.start || 1)
			this.initReader(this.current, this.start)
		},
		onUnload() {
			this.$utils.setFullscreen(false)
		},
		methods: {
			async initReader (current, start) {
				current = parseInt(current)
				start = parseInt(start)
				const chapter = await this.getContent(this.catalog[current], current)
				this.chapters.push(chapter)
				this.loading = false
				this.$nextTick(function () {
					uni.pageScrollTo({
						selector: '.comic_reader_image_' + start,
						duration: 100
					});
				})
			},
			async changeReader (current) {
				current = parseInt(current)
				const index = this.chapters.findIndex(c => c.index == current + 1)
				if ( index == -1 ) {
					this.loading = true
					const chapter = await this.getContent(this.catalog[current], current)
					this.chapters.push(chapter)
					this.loading = false
				}
				this.current = current
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0
				});
			},
			async getContent (chapter, index) {
				const request = this.context.request
				const params = Object.assign({}, this.detail, chapter)
				const staticData = this.context.staticData ? this.network.staticDataHandle(this.context.staticData, params) : {}
				const dynamicData = this.context.dynamicData || {}
				const newRequest = request ? this.network.requestHandle(request, params) : null
				const response = newRequest ? await this.network.$request(newRequest) : null
				const context = response ? await this.network.$list(dynamicData, response) : null
				return Object.assign({}, staticData, {
					index: index + 1,
					title: context.title || chapter.title || '第' + (index + 1) + '章',
					content: context.content,
					referer: context.referer || chapter.referer || this.detail.referer || '',
					isStart: index == 0,
					isEnd: index == this.catalog.length - 1
				})
			},
			handleChange (current) {
				this.start = current
			},
			handlePrev () {
				if ( this.current > 0 ) this.changeReader(this.current - 1)
				else uni.showToast({ title: '已经是第一话了', icon: 'none' })
			},
			handleNext () {
				if ( this.current < this.catalog.length - 1 ) this.changeReader(this.current + 1)
				else uni.showToast({ title: '已经是最后一话了', icon: 'none' })
			},
			handlePreview (src) {
				uni.previewImage({ urls: [src] })
			},
			handleCatalog () {
				this.$Router.push({
					path: '/pages/find/comic/chapter',
					query: {
						id: this.detail.uniqueId,
						list: this.catalog,
						title: this.detail.title || '',
						type: 'catalog',
						index: this.current,
					},
					animationType: 'slide-in-right',
					complete: () => {
						uni.$once('find_chapter', e => {
							this.changeReader(e.current)
						})
					}
				})
			},
			updatePositon () {
				openDB().then(() => {
					select('record', 'unique_id = "' + this.detail.uniqueId + '"').then(data=> {
						const record = data.list[0] || {}
						if ( record.id ) {
							update('record', {
								url: this.detail.url,
								title: this.detail.title || '',
								cover: this.detail.cover || '',
								current: this.current,
								position: this.start,
								currentTitle: this.currentChapter.title,
								is_adult: this.detail.isAdult,
								source_id: this.detail.sourceId
							}, 'id = ' + record.id).then(() => {
								closeDB()
								this.$Router.back()
							}).catch(err => {
								closeDB()
								uni.showToast({
									title: err.message,
									icon: 'none'
								})
								setTimeout(() => {
									this.$Router.back()
								}, 500)
							})
						} else {
							const params = {
								unique_id: this.detail.uniqueId,
								url: this.detail.url,
								title: this.detail.title || '',
								cover: this.detail.cover || '',
								current: this.current,
								position: this.start,
								current_title: this.currentChapter.title,
								is_adult: this.detail.isAdult,
								source_id: this.detail.sourceId
							}
							insert('record', params).then(() => {
								closeDB()
								this.$Router.back()
							}).catch(err => {
								closeDB()
								uni.showToast({
									title: err.message,
									icon: 'none'
								})
								setTimeout(() => {
									this.$Router.back()
								}, 500)
							})
						}
					}).catch(err => {
						closeDB()
						uni.showToast({
							title: err.message,
							icon: 'none',
							complete: () => {
								this.$Router.back()
							}
						})
					})
				})
			},
			handleCancel () {
				this.$Router.back()
			},
			handleSetFontSize (value) {
				const fontSize = this.fontSize + value
				if ( fontSize < 15 ) return
				if ( fontSize > 35 ) return
				this.$store.commit('setting/SET_DOCUMENT_FONT_SIZE', fontSize)
			},
			handleSetTheme (theme) {
				this.$store.commit('setting/SET_DOCUMENT_BG_COLOR', theme.bgColor)
				this.$store.commit('setting/SET_DOCUMENT_TEXT_COLOR', theme.color)
			}
		},
		onBackPress(event) {
			if ( event.from == 'backbutton' ) {
				if ( this.modalShow ) {
					this.modalShow = false
					return true
				}
				if ( this.settingShow ) {
					this.settingShow = false
					return true
				}
				if ( this.controlsShow ) {
					this.controlsShow = false
					return true
				}
				if ( this.currentChapter && this.currentChapter.content ) {
					if ( this.history == 0 ) {
						this.modalShow = true
					} else if ( this.history == 1 ) this.updatePositon()
					else this.$Router.back()
					return true
				}
			}
			return false
		}
	}
</script>

<!-- #ifdef H5 || APP-VUE -->
<script lang="renderjs" module="comic" type="module">
	export default {
		data () {
			return {
				content: '',
				whole: null
			}
		},
		mounted () {
			window.addEventListener('scroll', (e) => {
				const scrollTop = window.pageYOffset || document.documentElement.scrollTop
				const images = document.querySelectorAll('.comic_reader_image')
				let current = 0
				for ( let i = 0; i < images.length; i++ ) {
					const img = images[i]
					if ( scrollTop >= img.offsetTop ) current = i
				}
				this.triggerMethod('handleChange', current + 1)
			  // 滚动事件触发后执行的代码
			});
		},
		methods: {
			triggerMethod (name, args) {
				// #ifndef H5
				this.$ownerInstance.callMethod(name, args)
				// #endif
				// #ifdef H5
				this[name](args)
				// #endif
			}
		}
	}
</script>
<!-- #endif -->

<style>
@keyframes local-document-nav-bar-show {
	from {
		transform: translateY(-100%);
	}
	to {
		transform: translateY(0);
	}
}
@keyframes local-document-tabbar-show {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}
.comic-reader-center {
	width: 200rpx;
	height: 200rpx;
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}
.local-ducment-nav-bar-box {
	box-shadow: 0 0 20px rgba(0,0,0,.2);
	animation: local-document-nav-bar-show .3s both;
}
.local-ducment-tabbar-box{
	box-shadow: -10px 0 20px rgba(0,0,0,.2);
	animation: local-document-tabbar-show .3s both;
}
</style>